//
//  HomeViewController.swift
//  Community
//
//  Created by Vampire on 2019/7/18.
//  Copyright © 2019 ZKJ. All rights reserved.
//

import UIKit




class SWPTHomeViewController: BaseViewController {
    
    
    var clousre : MKPositioningClosure?
    private var locationManager : CLLocationManager?
    private var source : NSArray? = nil
    private let week  = UILabel()
    private let date = UILabel()
    private let wea = UILabel()
    private let weaImage = UIImageView()
    private let area = UILabel()

    private let headerView = HomeHeaderView.loadFromNib()
    private let topImageView = UIImageView()
    private var viewController : UIViewController?

    override func viewWillAppear(_ animated: Bool) {
        super .viewWillAppear(animated)
        self .startPositioning(self)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    
        self.fd_prefersNavigationBarHidden = true
        setupNavi()
        setupTableView()
        setupHeader()
        
    }
   
}

extension SWPTHomeViewController:  CLLocationManagerDelegate {
    
    internal func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            self.locationManager?.stopUpdatingLocation()
            
            let location = locations.last ?? CLLocation()
            let geocoder = CLGeocoder()
            
            geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
                
                if error != nil {
                    if self.clousre != nil {
                        self.clousre!(error?.localizedDescription ?? "")
                    }
                    return
                }
                
                if let place = placemarks?[0]{
                    
                    // 国家 省  市  区  街道  名称  国家编码  邮编
                    //                let country = place.country ?? ""
                    let lo:String = (place.locality != nil) ? place.locality! : "东莞"
                    let locality = "https://www.tianqiapi.com/api/?appid=24198181&appsecret=s53KVi1R&version=v1&city=" + lo
                    self.area.text =  lo
                    NetWorkRequest.sharedInstance.postWithRequest(UrlString:locality , paramer: nil, success: { (obj) in
                        
                        
                        self.source = weatherModel.mj_objectArray(withKeyValuesArray: obj["data"])
                        
                        guard let model = self.source?.firstObject as? weatherModel else {
                            return
                        }
                        
                        self.week.text = model.week
                        self.wea.text = model.wea
                        self.date.text = model.date.replacingOccurrences(of: "2019-", with: "").replacingOccurrences(of: "-", with: "/")
                        if model.wea.contains("雨"){
                            self.weaImage.image = UIImage.init(named: "raining_518.22349936143px_1233920_easyicon.net")
                        }
                        if model.wea.contains("云"){
                            self.weaImage.image = UIImage.init(named: "windy_643.53377265239px_1216642_easyicon.net")
                        }
                        if model.wea.contains("阴"){
                            self.weaImage.image = UIImage.init(named: "windy_643.53377265239px_1216642_easyicon.net")
                        }
                        if model.wea.contains("晴"){
                            self.weaImage.image = UIImage.init(named: "sun_782px_1227512_easyicon.net")
                        }
                        if model.wea.contains("雪"){
                            self.weaImage.image = UIImage.init(named: "snowy_609.1024px_1216622_easyicon.net")
                        }
                        if model.wea.contains("雷"){
                            self.weaImage.image = UIImage.init(named: "thunder_743.05247376312px_1209912_easyicon.net")
                        }
                        
                        
                        }, failure: { (error) in
                       
                        })
                   
            }
        }

        func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
            reportLocationServicesAuthorizationStatus(status: status)
        }
        
        func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
            self.locationManager?.stopUpdatingLocation()
        }
    }
}

extension SWPTHomeViewController  {
   private func setupNavi() {
        topImageView.frame = CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: StatusBarHeight + 44)
        topImageView.backgroundColor = mainGreenColor
        
        self.view.addSubview(topImageView)
        
        self.area.frame = CGRect.init(x: 15, y: StatusBarHeight, width: topImageView.width - 30, height: 44)
        area.font = constant.kBlodFontSize(x: 18)
        topImageView.addSubview(self.area)
        area.textColor = UIColor.white
        area.textAlignment = NSTextAlignment.right
        
        self.weaImage.frame = CGRect (x: 15, y: StatusBarHeight, width: 44, height: 44)
        weaImage.contentMode = UIView.ContentMode.scaleAspectFit
        weaImage.image = UIImage.init(named: "raining_518.22349936143px_1233920_easyicon.net")
        topImageView.addSubview(weaImage)
        let tap = UITapGestureRecognizer.init { (obj) in
            let weather = weatherViewController()
            self.navigationController?.pushViewController(weather, animated: true)
        }
        topImageView.isUserInteractionEnabled = true
        topImageView.addGestureRecognizer(tap)
    }
    private
    func setupTableView() {
        self.tableView.frame = CGRect.init(x: 0, y: topImageView.n_maxY + 10, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - AllTopNavHeight - NavBarHeight - topImageView.height)
        self.tableView.backgroundColor = .clear
        self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView.register(UINib.init(nibName: "SWPTHomeNewsTableViewCell", bundle: nil), forCellReuseIdentifier: "SWPTHomeNewsTableViewCell")
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(StatusBarHeight + 44)
        }
        
        
    }
    private
    func setupHeader() {
        
        self.week.frame = CGRect.init(x: 15, y: 0, width: 60, height: 35)
        week.font = constant.kFontSize(x: 12)
        self.headerView.addSubview(self.week)
        week.textColor = UIColor.white
       
        
        
        self.date.frame = CGRect (x: week.right + 5, y: 0, width: 60, height: 35)
        date.font = constant.kFontSize(x: 12)
        self.headerView.addSubview(self.date)
        date.textColor = UIColor.white
       
        self.wea.frame = CGRect (x: date.right + 5, y: 0, width: topImageView.width - 30, height: 35)
        wea.right = SCREEN_WIDTH - 15
        wea.font = constant.kFontSize(x: 12)
        self.headerView.addSubview(self.wea)
        wea.textColor = UIColor.white
        wea.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview()
            make.height.equalTo(30)
        }
        week.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview()
            make.height.equalTo(30)
        }
        date.snp.makeConstraints { (make) in
            make.right.equalTo(self.week.snp.left).offset(-5)
            make.top.equalToSuperview()
            make.height.equalTo(30)
        }
        
        self.headerView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 120)
        self.tableView.tableHeaderView = headerView
        
        
        self.headerView.selected = {[weak self] (index) in
            if index == 0 {
                self?.navigationController?.pushViewController(SWPTGarbageCalssViewController(), animated: true)
            }else {
                 self?.navigationController?.pushViewController(ZhiShiViewController(), animated: true)
                
            }
        }
    }
}

extension SWPTHomeViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SWPTHomeNewsTableViewCell") as! SWPTHomeNewsTableViewCell
        if indexPath.row == 0 {
            cell.fillCell(lab: NSLocalizedString("什么是垃圾分类？", comment: ""), img: UIImage.init(named: "cell1.jpeg")!)
        }else if indexPath.row == 1{
            cell.fillCell(lab: NSLocalizedString("为什么要垃圾分类？", comment: ""), img: UIImage.init(named: "cell2.jpg")!)
        }else if indexPath.row == 2{
            cell.fillCell(lab: NSLocalizedString("怎么垃圾分类？", comment: ""), img: UIImage.init(named: "cell3.jpg")!)
        }
        
        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let web = WebViewController()
        if indexPath.row == 0 {
            web.title = NSLocalizedString("什么是垃圾分类？", comment: "")
            web.requst(path: "index1")
        }else if indexPath.row == 1{
            web.title = NSLocalizedString("为什么要垃圾分类？", comment: "")
            web.requst(path: "index2")
        }else if indexPath.row == 2{
            web.title = NSLocalizedString("怎么垃圾分类？", comment: "")
            web.requst(path: "index3")
        }
        self.navigationController?.pushViewController(web, animated: true)
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 220 //(SCREEN_HEIGHT - AllTopNavHeight - NavBarHeight - topImageView.height - 40)/3.0
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y <= 10 {
             self.topImageView.height = -scrollView.contentOffset.y + 100
        }
    }
}
private
extension SWPTHomeViewController {
    
    @objc func toWeather() {
        let weather = SWPTGarbageCalssViewController()
        self.navigationController?.pushViewController(weather, animated: true)
        
    }
    
    func startPositioning(_ vc:UIViewController) {
        viewController = vc
        if (self.locationManager != nil) && (CLLocationManager.authorizationStatus() == .denied) {
            // 定位提示
            alter(viewController: viewController!)
        } else {
            requestLocationServicesAuthorization()
        }
    }
    
    // 初始化定位
    private func requestLocationServicesAuthorization() {
        
        if (self.locationManager == nil) {
            self.locationManager = CLLocationManager()
            self.locationManager?.delegate = self as CLLocationManagerDelegate
        }
        
        self.locationManager?.requestWhenInUseAuthorization()
        self.locationManager?.startUpdatingLocation()
        
        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.notDetermined) {
            locationManager?.requestWhenInUseAuthorization()
        }
        
        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse) {
            locationManager?.desiredAccuracy = kCLLocationAccuracyBest
            let distance : CLLocationDistance = 10.0
            locationManager?.distanceFilter = distance
            locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager?.startUpdatingLocation()
        }
    }
    
    
    // 获取定位代理返回状态进行处理
    private func reportLocationServicesAuthorizationStatus(status:CLAuthorizationStatus) {
        
        if status == .notDetermined {
            // 未决定,继续请求授权
            requestLocationServicesAuthorization()
        } else if (status == .restricted) {
            // 受限制，尝试提示然后进入设置页面进行处理
            alter(viewController: viewController!)
        } else if (status == .denied) {
            // 受限制，尝试提示然后进入设置页面进行处理
            alter(viewController: viewController!)
        }
    }
    
    
    private func alter(viewController:UIViewController) {
        let alert = UIAlertController.init(title: "定位服务未开启,是否前往开启?", message: "请进入系统[设置]->[隐私]->[定位服务]中打开开关，并允许“赏金猎人”使用定位服务", preferredStyle: UIAlertController.Style.alert)
        
        let action = UIAlertAction.init(title: "YES", style: UIAlertAction.Style.default) { (act) in
            let url = URL(fileURLWithPath: UIApplication.openSettingsURLString)
            if UIApplication.shared.canOpenURL(url){
                UIApplication.shared.openURL(url)
            }
        }
        let action1 = UIAlertAction.init(title: "NO", style: UIAlertAction.Style.default) { (UIAlertAction) in
            
        }
        alert.addAction(action)
        alert.addAction(action1)
        self.present(alert, animated: true, completion: nil)
    }
}
